package com.uwo.commons.configuration.aop.validate.validate;

import com.uwo.commons.configuration.aop.validate.ErrorCode;
import com.uwo.commons.configuration.aop.validate.Validate;
import com.uwo.commons.configuration.aop.validate.ValidateField;
import com.uwo.commons.configuration.aop.validate.ValidateProperties;
import com.uwo.commons.kits.MatcherKits;
import com.uwo.commons.kits.StringKits;
import com.uwo.commons.configuration.aop.validate.excepteion.ApiValidateExceptrion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * 验证基类
 * @author hao.yan
 */
public class BaseValidate implements Validate {

    private final Logger log = LoggerFactory.getLogger(BaseValidate.class);

    private final String matcher = "^(\\{)((\\w)+.(\\w)+)+(\\})$";

    private final String matcherFind = "(?<=\\{)(.+?)(?=\\})";

    /**
     * 校验
     * @param annotation
     * @param validateField
     * @return
     * @throws ApiValidateExceptrion
     */
    public void validate(Annotation annotation, ValidateField validateField) throws ApiValidateExceptrion {

    }

    /**
     * 异常处理
     * @param code
     * @param message
     * @param errorCode
     * @param args
     * @throws ApiValidateExceptrion
     */
    protected void exception(int code, String message, ErrorCode errorCode) throws ApiValidateExceptrion {
        code = (code == 0) ? errorCode.getCode() : code;
        throw new ApiValidateExceptrion(code, message);
    }

    /**
     * 读取配置信息
     * @param properties
     * @param propertiesSuffix
     * @return
     */
    protected String message(Map<String, String> properties, String propertiesSuffix, String defaultMessage){
        return (properties.containsKey(propertiesSuffix)) ? properties.get(propertiesSuffix) : defaultMessage;
    }

    protected String value(Map<String, String> properties, String message, String defaultMessage){
        if(MatcherKits.matches(matcher, message)){
            String propertiesSuffix = MatcherKits.value(matcherFind, message);
            return message(properties, propertiesSuffix, defaultMessage);
        }
        return (StringKits.isEmpty(message))? defaultMessage: message;
    }

}
